package ru.mcfr.oxygen.updater.plugin;

import org.apache.log4j.Logger;
import ro.sync.exml.plugin.workspace.WorkspaceAccessPluginExtension;
import ro.sync.exml.workspace.api.standalone.MenuBarCustomizer;
import ro.sync.exml.workspace.api.standalone.StandalonePluginWorkspace;
import ru.mcfr.oxygen.updater.UpdateProcessor;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.net.URL;


public class UpdateManagerExtension implements WorkspaceAccessPluginExtension {

    Thread updater;
	
	private static Logger logger = Logger.getLogger(UpdateManagerExtension.class.getName());
	
	private StandalonePluginWorkspace instance = null;

	private boolean runPlugin;

	public boolean applicationClosing() {
        try{
            updater.interrupt();
        } finally {
            return true;
        }
	}

	public void applicationStarted(final StandalonePluginWorkspace pluginWorkspaceAccess) {

        //update steps:
        //1.1 download from server files to local storage
        //1.2 make arc copy of work files
        //1.3 unpack new version

        //2.1 upload information about oXygen (path's, settings)
        //2.2 download settings from server
        //2.3 compare with this copy
        //2.4 if difference in key values apply new settings

		this.instance = pluginWorkspaceAccess;



        String mainPath = UpdateManagerPlugin.getInstance().getDescriptor().getBaseDir().getPath();

        String systemPath = UpdateManagerPlugin.getInstance().getDescriptor().getBaseDir().getParentFile().getParentFile().getPath();


        final UpdateProcessor processor = UpdateProcessor.getInstance(mainPath, systemPath);

        updater = new Thread() {
            public void run() {
                while (true) {
                    try {
                        pluginWorkspaceAccess.showStatusMessage(processor.run());
                        sleep(1000 * 60 * Integer.valueOf(processor.getProperty("update-per-minutes", "120")));
                    } catch (Exception e) {
                        pluginWorkspaceAccess.showStatusMessage(e.getLocalizedMessage());
                        e.printStackTrace();
                        System.err.println(e.getLocalizedMessage());
                    }
                }
            }
        };

		URL resource = getClass().getResource("/" + getClass().getName().replace('.', '/') + ".class");
		
		this.runPlugin = "jar".equals(resource.getProtocol()) ? true : System.getProperty("ru.mcfr.updater") != null;
		if (runPlugin) {
            System.setProperty("ru.mcfr.updater", "true");
            updater.start();


			pluginWorkspaceAccess.addMenuBarCustomizer(new MenuBarCustomizer() {

				final Action showSettingsWindow = new AbstractAction() {

					public void actionPerformed(ActionEvent e) {

						processor.showSettingsDialog();

					}

				};

				public void customizeMainMenu(JMenuBar mainMenuBar) {

					JMenu menuCMS = new JMenu();
					final JMenuItem oneMenuItem = new JMenuItem(showSettingsWindow);
					oneMenuItem.setText("Настройки");
					menuCMS.add(oneMenuItem);
					menuCMS.setText("Обновления");

					mainMenuBar.add(menuCMS, mainMenuBar.getMenuCount() - 1);
				}
			});
		}
	}

}
